package com.geekcc.springboot.controller;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.geekcc.springboot.common.Result;
import com.geekcc.springboot.entity.Supplier;
import com.geekcc.springboot.service.SupplierService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/supplier")
public class SupplierController {

    @Autowired
    private SupplierService supplierService;

    //根据ID查询
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(supplierService.getById(id));
    }

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Supplier supplier) {
        return Result.success(supplierService.saveOrUpdate(supplier));
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        return Result.success(supplierService.removeById(id));
    }

    // 批量删除
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {    // [1,2,3]
        return Result.success(supplierService.removeByIds(ids));
    }

    @GetMapping
    public Result findAll() {
        return Result.success(supplierService.list());
    }

    @GetMapping("name/{name}")
    public Result findOne(@PathVariable String name) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",name);
        return Result.success(supplierService.getOne(queryWrapper));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(defaultValue = "") String name,
                           @RequestParam(defaultValue = "") String remarks,
                           @RequestParam(defaultValue = "") String address,
                           @RequestParam(defaultValue = "") String contact) {
        QueryWrapper<Supplier> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("name", name);
        }
        if (!"".equals(remarks)) {
            queryWrapper.like("remarks", remarks);
        }
        if (!"".equals(address)) {
            queryWrapper.like("address", address);
        }
        if (!"".equals(contact)) {
            queryWrapper.like("contact", contact);
        }
//        Page<Supplier> page = new Page<>(pageNum, pageSize);
//        return Result.success(supplierService.page(page,queryWrapper));
        return Result.success(supplierService.page(new Page<>(pageNum, pageSize), queryWrapper));

    }

    // 导出接口（运用hutool）
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        // 从数据库查询出所有的数据
        List<Supplier> list = supplierService.list();
        // 通过工具类创建writer写出到磁盘路径
//        ExcelWriter writer = ExcelUtil.getWriter(fileUploadPath + "/用户信息.xlsx");
        // 在内存操作，写出到浏览器
        ExcelWriter writer = ExcelUtil.getWriter(true);

        //一次性写出list内的对象到Excel，使用默认样式，强制输出标题
        writer.write(list, true);

        // 设置浏览器响应的格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("用户信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        out.close();
        writer.close();

    }

    // 导入接口
    @PostMapping("/import")
    public Result imp(MultipartFile file) throws Exception {
        InputStream inputStream = file.getInputStream();
        ExcelReader reader = ExcelUtil.getReader(inputStream);

        List<Supplier> list = reader.read(0, 1, Supplier.class);

        System.out.println(list);

        supplierService.saveBatch(list);
        return Result.success(true);
    }

}
